import re
import sys
from functools import partial

import PySide6
from PySide6.QtCore import Qt, QRegularExpression
from PySide6.QtGui import QIcon, QRegularExpressionValidator
from PySide6.QtWidgets import QWidget, QGridLayout, QTableWidget, QLabel, QLineEdit, QPushButton, QHBoxLayout, QFrame, \
    QVBoxLayout, QTableWidgetItem, QApplication, QMessageBox, QComboBox, QSizePolicy

import resources.resources_rc  # 导入图片资源不可去
from main_ui.dock_scope import AgeValidator


class Channel_Manage(QWidget):
    def __init__(self, parent=None, config=None):
        super(Channel_Manage, self).__init__()
        # 获取变量
        self.config = config
        self.signal_operat = parent.signal_operat

        # 创建变量
        self.channels_num = 100
        self.change_flag = False  # 记录表格是否有改动
        self.combox_dict = {'100us': 1,
                            '200us': 2,
                            '400us': 4,
                            '500us': 5,
                            '1ms': 10,
                            '2ms': 20,
                            '2.5ms': 25,
                            '5ms': 50,
                            '10ms': 100
                            }
        self.fresh_frequency_dict = {'50ms': 50,
                                     '100ms': 100,
                                     '200ms': 200
                                     }

        # 生成视图
        self.initLayout()

        # 为表格添加数据
        self.add_table_data()

        self.change_flag = False
        self.show()

    def initLayout(self):
        """ 创建table视图 和 添加保存 按钮 """
        self.setWindowTitle('通道管理')
        self.setWindowIcon(QIcon(':/logo.ico'))
        self.setMinimumHeight(400)
        self.setMinimumWidth(380)
        # self.setFixedWidth(270)
        self.layout = QVBoxLayout(self)

        # 创建table
        self.table_scope = QTableWidget(self.channels_num, 3)
        self.table_scope.verticalHeader().setVisible(False)
        self.table_scope.setHorizontalHeaderLabels(['通道号', '通道名称', '成员名称'])
        self.table_scope.setColumnWidth(0, 100)
        self.table_scope.setColumnWidth(1, 110)
        self.table_scope.setColumnWidth(2, 110)
        self.layout.addWidget(self.table_scope)

        # 创建下方的frame
        self.frame = QFrame()
        self.frame.setLineWidth(1)
        self.frame.setContentsMargins(0, 0, 0, 0)
        self.frame.setFixedHeight(95)
        self.frame_layout = QGridLayout(self.frame)
        self.layout.addWidget(self.frame)

        # 创建通道数量
        temp_layout = QGridLayout()
        self.label_channel_num = QLabel('通道数量:')
        self.edit_channel_num = QLineEdit()
        self.edit_channel_num.textChanged.connect(self.func_channel_count_text_change)
        intValidator = AgeValidator(self.channels_num)
        self.edit_channel_num.setValidator(intValidator)
        self.edit_channel_num.setFixedWidth(80)
        temp_layout.addWidget(self.label_channel_num, 0, 0, 1, 1)
        temp_layout.addWidget(self.edit_channel_num, 0, 1, 1, 1)
        self.frame_layout.addLayout(temp_layout, 0, 0, 2, 3, Qt.AlignCenter)

        # 创建采样间隔
        temp_layout = QGridLayout()
        self.label_time_interval = QLabel('采样间隔:')
        self.label_time_interval.setFixedWidth(80)
        self.combox_time_interval = QComboBox()
        self.combox_time_interval.currentIndexChanged.connect(self.func_paras_changed)
        self.combox_time_interval.addItems(list(self.combox_dict.keys()))
        self.combox_time_interval.setFixedWidth(80)

        temp_layout.addWidget(self.label_time_interval, 0, 0, 1, 1)
        temp_layout.addWidget(self.combox_time_interval, 0, 1, 1, 1)
        self.frame_layout.addLayout(temp_layout, 2, 0, 2, 3, Qt.AlignCenter)

        # 创建波形视图刷新频率
        temp_layout = QGridLayout()
        self.label_scope_refresh_frequency = QLabel('视图刷新频率:')
        self.label_scope_refresh_frequency.setFixedWidth(80)
        self.combox_scope_refresh_frequency = QComboBox()
        self.combox_scope_refresh_frequency.currentIndexChanged.connect(self.func_paras_changed)
        self.combox_scope_refresh_frequency.addItems(list(self.fresh_frequency_dict.keys()))
        self.combox_scope_refresh_frequency.setFixedWidth(80)


        # self.edit_scope_refresh_frequency = QLineEdit()
        # self.edit_scope_refresh_frequency.textChanged.connect(self.func_paras_changed)
        # intValidator = AgeValidator(1000)
        # self.edit_channel_num.setValidator(intValidator)
        # self.edit_scope_refresh_frequency.setFixedWidth(80)
        temp_layout.addWidget(self.label_scope_refresh_frequency, 0, 0, 1, 1)
        temp_layout.addWidget(self.combox_scope_refresh_frequency, 0, 1, 1, 1)
        self.frame_layout.addLayout(temp_layout, 4, 0, 2, 3, Qt.AlignCenter)

        # 创建恢复默认按钮
        self.button_default = QPushButton('恢复默认')
        self.button_default.setFixedSize(65, 35)
        self.button_default.clicked.connect(self.func_button_default)
        self.frame_layout.addWidget(self.button_default, 0, 3, 3, 1, Qt.AlignCenter)

        # 创建保存按钮
        self.button_save = QPushButton('保存')
        self.button_save.setFixedSize(65, 35)
        self.button_save.clicked.connect(self.func_button_save)
        self.frame_layout.addWidget(self.button_save, 3, 3, 3, 1, Qt.AlignCenter)

    def add_table_data(self):
        """ 为表格添加列，并从config当中读取数据，如果config为空设置默认 """
        for i in range(self.channels_num):
            item1 = QLabel(str(i))
            item1.setAlignment(Qt.AlignCenter)
            self.table_scope.setCellWidget(i, 0, item1)
            if self.config:
                item2 = QLineEdit(self.config['channel_name'][i])
            else:
                item2 = QLineEdit('通道' + str(i))
            item2.setAlignment(Qt.AlignCenter)
            item2.setFixedWidth(110)
            item2.textChanged.connect(self.func_paras_changed)
            item2.editingFinished.connect(partial(self.item2_text_change, i))
            self.table_scope.setCellWidget(i, 1, item2)
            item3 = QLineEdit()
            c_variable_pattern = QRegularExpression(r'^[a-zA-Z_][a-zA-Z0-9_]*$')  # C语言变量命名规范的正则表达式
            validator = QRegularExpressionValidator(c_variable_pattern)
            item3.setValidator(validator)
            item3.setAlignment(Qt.AlignCenter)
            item3.textChanged.connect(self.func_paras_changed)
            item3.editingFinished.connect(partial(self.item3_text_change, i))
            if self.config and 'member_name' in self.config.keys():
                if self.config['channel_name'][i][0:2] == '通道':
                    item3.setText('CH' + str(i))
                else:
                    item3.setText(self.config['member_name'][i])
            elif self.config and 'channel_name' in self.config.keys() and self.is_valid_c_identifier(self.config['channel_name'][i]):
                item3.setText(self.config['channel_name'][i])
            else:
                item3.setText('CH' + str(i))
            # item3.setText('var' + str(i))
            item3.setFixedWidth(110)
            self.table_scope.setCellWidget(i, 2, item3)

        if self.config:
            self.edit_channel_num.setText(self.config['channel_num'])
            # self.edit_scope_refresh_frequency.setText(self.config['scope_refresh_frequency'])
            if 'scope_refresh_frequency' in list(self.config.keys()):
                self.combox_scope_refresh_frequency.setCurrentIndex(list(self.fresh_frequency_dict.values()).index(int(self.config['scope_refresh_frequency'])))
            if 'scope_interval' in list(self.config.keys()):
                self.combox_time_interval.setCurrentIndex(
                    list(self.combox_dict.values()).index(self.config['scope_interval']))
        else:
            self.edit_channel_num.setText('50')
            # self.edit_scope_refresh_frequency.setText('100')

    def is_valid_c_identifier(self, s):
        # 使用正则表达式匹配 C 语言的标识符规则
        pattern = r'^[a-zA-Z_][a-zA-Z0-9_]*$'
        return bool(re.match(pattern, s))

    def func_channel_count_text_change(self):
        """ 关联通道个数改变的信号 """
        self.change_flag = True
        if self.edit_channel_num.text().isdigit():
            channel_num = int(self.edit_channel_num.text())
            if channel_num % 2 == 0:
                for i in range(self.channels_num):
                    if i < channel_num:
                        self.table_scope.cellWidget(i, 0).setEnabled(True)
                        self.table_scope.cellWidget(i, 1).setEnabled(True)
                        self.table_scope.cellWidget(i, 2).setEnabled(True)
                    else:
                        self.table_scope.cellWidget(i, 0).setEnabled(False)
                        self.table_scope.cellWidget(i, 1).setEnabled(False)
                        self.table_scope.cellWidget(i, 2).setEnabled(True)

    def func_button_save(self):
        """ 保存的关联函数 """
        # 判断输入的通道数
        if self.edit_channel_num.text():
            # if int(self.edit_channel_num.text()) % 2 != 0:
            #     QMessageBox.warning(self, "提示", "请保证输入通道个数为2的倍数!", QMessageBox.Yes)
            #     return
            if int(self.edit_channel_num.text()) > self.channels_num:
                QMessageBox.warning(self, "提示", "请输入有效的通道数!", QMessageBox.Yes)
                return
        else:
            QMessageBox.warning(self, "提示", "请输入通道个数!", QMessageBox.Yes)
            return

        # # 判断输入的刷新率
        # if self.edit_scope_refresh_frequency.text():
        #     if int(self.edit_scope_refresh_frequency.text()) < 40:
        #         QMessageBox.warning(self, "提示", "输入的刷新频率请超过40ms!", QMessageBox.Yes)
        #         return
        #     if int(self.edit_scope_refresh_frequency.text()) > 2000:
        #         QMessageBox.warning(self, "提示", "输入的刷新频率请不要超过2000!", QMessageBox.Yes)
        #         return
        # else:
        #     QMessageBox.warning(self, "提示", "请输入刷新频率!", QMessageBox.Yes)
        #     return

        # 存储通道个数，间隔时间和刷新率
        if not self.config:
            self.config = {}
        # self.config['scope_refresh_frequency'] = self.edit_scope_refresh_frequency.text()
        self.config['scope_refresh_frequency'] = self.fresh_frequency_dict[self.combox_scope_refresh_frequency.currentText()]
        self.config['scope_interval'] = self.combox_dict[self.combox_time_interval.currentText()]
        self.config['channel_num'] = self.edit_channel_num.text()

        # 存储通道名称
        name_list = []
        for i in range(self.channels_num):
            if self.table_scope.cellWidget(i, 1).text():
                if self.table_scope.cellWidget(i, 1).text() == '通道' + str(i + 1):
                    name_list.append('通道' + str(i))
                else:
                    name_list.append(self.table_scope.cellWidget(i, 1).text())
            else:
                name_list.append('通道' + str(i))

        self.config['channel_name'] = name_list

        # 存储成员列表名称
        name_list2 = []
        for i in range(self.channels_num):
            if self.table_scope.cellWidget(i, 2).text():
                name_list2.append(self.table_scope.cellWidget(i, 2).text())
            else:
                name_list2.append('var' + str(i))

        self.config['member_name'] = name_list2
        # print(self.config)
        self.signal_operat.emit(1, 1, [self.config])
        # self.change_flag = False
        QMessageBox.information(self, "提示", "保存成功!", QMessageBox.Yes)

        # 将处理后的数据返回回去显示
        self.add_table_data()
        self.change_flag = False
        return True

    def func_button_default(self):
        """ 恢复默认的关联函数 """
        self.change_flag = True
        reply = QMessageBox.question(self, '提示', '是否要恢复默认设置!', QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            # for i in range(self.channels_num):
            #     self.table_scope.cellWidget(i, 1).setText('通道' + str(i))
            #     self.table_scope.cellWidget(i, 2).setText('var' + str(i))
            self.edit_channel_num.setText('40')
            self.edit_scope_refresh_frequency.setText('100')
        else:
            pass


    def item2_text_change(self, idx):
        text = self.table_scope.cellWidget(idx, 1).text()
        print(text)
        if self.is_valid_c_identifier(text):
            for i in range(self.channels_num):
                if i != idx:
                    if self.table_scope.cellWidget(i, 1).text() == text:
                        QMessageBox.warning(self, "提示", "请保证通道名称唯一!", QMessageBox.Yes)
                        self.table_scope.cellWidget(idx, 1).setText(self.config['channel_name'][idx])
                        return
            self.table_scope.cellWidget(idx, 2).setText(text)

    def item3_text_change(self,idx):
        text = self.table_scope.cellWidget(idx, 2).text()
        print(text)
        if self.is_valid_c_identifier(text):
            for i in range(self.channels_num):
                if i != idx:
                    if self.table_scope.cellWidget(i, 2).text() == text:
                        QMessageBox.warning(self, "提示", "请保证通道名称唯一!", QMessageBox.Yes)
                        self.table_scope.cellWidget(idx, 2).setText(self.config['member_name'][idx])
                        return



    def func_paras_changed(self):
        """ 记录表格是否有未保存的改动 """
        self.change_flag = True

    def closeEvent(self, event: PySide6.QtGui.QCloseEvent) -> None:
        if self.change_flag:
            reply = QMessageBox.warning(self,
                                        "提示",
                                        "可能有未保存的变动\n是否保存并退出",
                                        QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
            if reply == QMessageBox.Yes:
                if self.func_button_save():
                    event.accept()
                else:
                    event.ignore()
                    return
            elif reply == QMessageBox.No:
                event.accept()
            else:
                event.ignore()
                return
        else:
            event.accept()
        self.signal_operat.emit(1, 0, [None])


if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = Channel_Manage()  # scaleRate)
    myWin.show()
    sys.exit(app.exec())
